﻿using System;
using System.Collections.Generic;
using System.Windows;
#if WPF
using System.Windows.Media;
#endif

public static class CommonExtentions
{
    #region 异常处理
    public static Exception GetInnerException(this Exception e)
    {
        var innerException = e;
        while (innerException.InnerException != null)
        {
            innerException = innerException.InnerException;
        }
        return innerException;
    }
    public static string GetMessage(this Exception e, bool includeStackTrace = false)
    {
        string message = e.Message + "\r\n";
        if (includeStackTrace)
        {
            message += e.StackTrace + Environment.NewLine;
        }
        var innerException = e.InnerException;
        while (innerException != null)
        {
            message += "----------------------------------------" + Environment.NewLine;
            message += innerException.Message + "\r\n";
            if (includeStackTrace) message += innerException.StackTrace + "\r\n";
            innerException = innerException.InnerException;
            if (includeStackTrace)
            {
                message += e.StackTrace + Environment.NewLine;
            }
        }
        return message;
    }
    #endregion

#if WPF
    #region 可视树，逻辑树
    public static List<T> GetVisualTree<T>(this DependencyObject obj, int depth = 0) where T : DependencyObject
    {
        List<T> lists = new List<T>();
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            var element = VisualTreeHelper.GetChild(obj, i);
            if (element != null)
            {
                if (element is T)
                {
                    lists.Add(element as T);
                }
                lists.AddRange(GetVisualTree<T>(element, depth + 1));
            }
        }
        return lists;
    }

    public static List<T> GetLogicTree<T>(this DependencyObject obj) where T : DependencyObject
    {
        List<T> lists = new List<T>();
        var enumerator = LogicalTreeHelper.GetChildren(obj).GetEnumerator();
        while (enumerator.MoveNext())
        {
            var element = enumerator.Current;
            if (element != null)
            {
                if (element is T)
                {
                    if (element is T)
                    {
                        lists.Add(element as T);
                    }
                    lists.AddRange(GetLogicTree<T>(element as DependencyObject));
                }
            }
        }
        return lists;
    }
    #endregion
#endif
}

